<template>
  <div>
    <a-modal :width="720" title="选择人员" :visible="visible" @ok="ok" @cancel="$emit('update:visible', false)">
      <a-spin :spinning="spinning">
        <div class="employee-selector-wrapper2">
          <div>
            <div class="employee-selector-block">
              <a-input-search placeholder="请输入" style="width: 100%" v-model="search" @search="onSearch" @change="onSearchChange" />
            </div>
            <div class="tit mt12">
              <div
                v-for="item in tabArr"
                :key="item.id"
                class="hrs-tabs"
                :class="tabStatus == item.id ? 'hrs-tabs-selectStyle' : ''"
                @click="onTabs(item.id)"
              >
                {{ item.name }}
              </div>
              <!-- <div class="mr4">*</div>
              <div>选择指定的用工单位进行职位内推，未选择的用工单位无法内推该职位</div> -->
            </div>
            <div class="tree-item2" style="margin-top: 20px">
              <div>全选当页</div>
              <a-checkbox :checked="isAllSelected" @change="choseAll(treeData)" style="margin-left: 10px"></a-checkbox>
              <!-- <xq-icon type="icon-wancheng2" v-if="isAllSelected" @click="choseAll(treeData)" class="iconStyle" style="margin-left: 10px;">
              </xq-icon>
              <img v-else @click="choseAll(treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;margin-left:10px" /> -->
            </div>
            <div class="employee-selector" style="position: relative">
              <div v-for="(item, index) in treeData" :key="index">
                <div class="tree-item" :class="item.isSelected ? 'selectStyle' : ''" @click="chose(item, treeData)">
                  <div class="tree-item-div">
                    <!-- <img src="@/assets/icons/person1.png" style="width:30px;height:30px;margin-right:10px" /> -->
                    <a-tooltip placement="top">
                      <template slot="title">
                        <span>{{ item.name }}</span>
                      </template>
                      <div class="overflows overflowsWL">
                        {{ item.name }}
                      </div>
                    </a-tooltip>
                    <div class="overflows overflowsWLM">{{ item.phone }}</div>
                  </div>
                  <span class="checkboxs">
                    <span @click.stop="chose(item, treeData)"></span>
                    <a-checkbox :checked="item.isSelected"></a-checkbox>
                  </span>
                  <!-- <xq-icon v-on:click.stop="chose(item, treeData)" type="icon-wancheng2" v-if="item.isSelected" class="iconStyle">
                  </xq-icon>
                  <img v-else v-on:click.stop="chose(item, treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;" /> -->
                </div>
              </div>
            </div>
            <a-pagination
              v-model="current"
              size="small"
              :page-size-options="pageSizeOptions"
              :total="total"
              show-size-changer
              show-less-items
              :page-size="pageSize"
              @showSizeChange="onShowSizeChange"
              @change="onPageChange"
              style="margin-top: 12px; text-align: right"
            >
              <template slot="buildOptionText" slot-scope="props">
                <span>{{ props.value }}条/页</span>
              </template>
            </a-pagination>
          </div>

          <div class="employee-selector-block2">
            <div class="employee-selector-title">
              <div>
                已经选择 <span class="selectStyle">{{ selectedListTemp.length }}</span> 人
              </div>
              <a-button type="link" v-if="selectedListTemp.length" @click="remove"> 清除 </a-button>
            </div>
            <div class="employee-selector">
              <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
                <div class="tree-item">
                  <div class="tree-item-div">
                    <!-- <img src="@/assets/icons/person1.png" style="width:30px;height:30px;margin-right:10px" /> -->
                    <a-tooltip placement="top">
                      <template slot="title">
                        <span>{{ item.name }}</span>
                      </template>
                      <div class="overflows overflowsWR">
                        {{ item.name }}
                      </div>
                    </a-tooltip>
                  </div>
                </div>
                <img @click="deleteItem(item, i)" src="@/assets/icons/删除.png" style="width: 14px; height: 14px; cursor: pointer" />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getTransferAccountsPeoples, getPageOnJobEmpList, postBuildDetailAddDTOList } from "../api";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedList: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: ""
    },
    companyId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      search: "",
      spinning: false,
      treeData: [],
      selectedListTemp: [],
      isAllSelected: false,
      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 10,
      current: 1,
      total: 0,
      tabStatus: 1,
      tabArr: [
        { id: 1, name: "发薪人员库" },
        { id: 2, name: "用工花名册" }
      ]
    };
  },
  watch: {
    visible(val) {
      if (val) {
        // setTimeout(() => {
        // });
        this.selectedListTemp = [];
        this.search = "";
        this.current = 1;
        this.spinning = false;
        this.tabStatus = 1;
        this.getSelectDepTree("visibleinit");
      }
    }
  },

  methods: {
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    remove() {
      this.spinning = true;
      for (let i = 0, len = this.treeData.length; i < len; i++) {
        this.treeData[i].isSelected = false;
        this.ergodicAll(this.treeData[i]);
      }
      this.isAllSelected = false;
      this.selectedListTemp = [];
      setTimeout(() => {
        this.spinning = false;
      }, 10);
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }

      setTimeout(function() {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function() {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
      var count = this.treeData.length;
      var allSelect = true;
      for (var i = 0; i < count; i++) {
        if (!this.treeData[i].isSelected) {
          allSelect = false;
          break;
        }
      }
      this.isAllSelected = allSelect;
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex(it => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex(it => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },
    onTabs(id) {
      this.current = 1;
      this.tabStatus = id;
      this.getSelectDepTree();
    },
    // 获取树
    async getSelectDepTree(query) {
      try {
        const params = {
          pageSize: this.pageSize,
          pageNo: this.current,
          "orders[0].property": "gmtCreate",
          "orders[0].desc": true
        };

        // if (this.tabStatus === 2) params.companyId = this.companyId ? this.companyId : this.$store.state.hr.companyId;
        if (this.tabStatus === 2) params.companyId = this.companyId;
        this.spinning = true;
        let fun = null;
        if (this.tabStatus === 1) {
          params.queryType = 1;
          params.nameOrPhoneOrIdCard = this.search;
          fun = getTransferAccountsPeoples;
        } else {
          params.nameOrPhone = this.search;
          fun = getPageOnJobEmpList;
        }
        const { data } = await fun(params);
        if (data === null) {
          this.$message.warning("暂无数据");
          this.treeData = [];
          this.total = 0;
          this.isAllSelected = false;
        } else {
          this.treeData = this.formatCompanyData(data.entities);
          this.total = data.entityCount;
          const count = data.entities.length;
          let allSelect = true;
          this.spinning = false;
          if (count !== 0) {
            if (query && query === "visibleinit") {
              this.selectedList.forEach(e => {
                this.treeData.forEach(m => {
                  if (e.id === m.id) {
                    m.isSelected = true;

                    // this.selectedListTemp.push(m);
                  }
                });
              });
              this.selectedListTemp = JSON.parse(JSON.stringify(this.selectedList));
            } else {
              this.selectedListTemp.forEach(e => {
                this.treeData.forEach(m => {
                  if (e.id === m.id) {
                    m.isSelected = true;
                  }
                });
              });
            }
            this.treeData.some(e => {
              if (!e.isSelected) {
                allSelect = false;
                return true;
              }
            });

            this.isAllSelected = allSelect;
          } else {
            this.isAllSelected = false;
          }
        }

        this.spinning = false;
      } catch (err) {
        this.spinning = false;
        console.log("error log --> ", err);
      }
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;

        this.selectedListTemp.forEach((item, index) => {
          if (item.id === company[key].id) {
            selected = true;
          }
        });
        var emp = {};

        emp = {
          id: company[key].id,
          name: company[key].name,
          phone: company[key].phone,
          type: this.tabStatus
        };

        this.selectedListTemp.forEach((item, index) => {
          item.isSelected = true;
        });

        parent.push(emp);
      }
      return parent;
    },
    onSearch() {
      this.current = 1;
      this.getSelectDepTree();
    },
    onSearchChange(e) {
      this.current = 1;
      if (e.target.value === "") {
        this.getSelectDepTree();
      }
    },
    deleteItem(item, index) {
      // this.treeData[index].isSelected = false;
      item.isSelected = false;
      this.treeData.forEach((item2, index2) => {
        if (item2.id === item.id) {
          this.treeData[index2].isSelected = false;
        }
      });
      this.treeData = JSON.parse(JSON.stringify(this.treeData));
      this.spinning = true;

      var that = this;
      setTimeout(function() {
        that.$nextTick(() => {
          that.ergodic(item);
        });

        that.spinning = false;
      }, 100);
    },
    ok() {
      // if (this.selectedListTemp.length === 0) {
      //   this.$message.warning("请选择人员");
      //   return;
      // }
      // if (this.selectedListTemp.length > this.limitNum) {
      //   this.$message.success(`一次性最多选择${this.limitNum}人`);
      //   return;
      // }
      // const arr = this.selectedListTemp.map(item => item.id);
      if (this.type === "info") {
        this.onPostBuildDetailAddDTOList();
      } else {
        this.$emit("update:visible", false);
        this.$emit("upDate", this.selectedListTemp);
      }
    },
    async onPostBuildDetailAddDTOList(v) {
      try {
        // this.confirmLoading = true;

        const selectedListTemp = JSON.parse(JSON.stringify(this.selectedListTemp));
        selectedListTemp.map(e => {
          delete e.name;
          delete e.phone;
          delete e.isSelected;
        });
        const info = JSON.parse(sessionStorage.getItem("paySalaryInfo"));
        const paySalaryInfoId = sessionStorage.getItem("paySalaryInfoId");
        const { data } = await postBuildDetailAddDTOList({
          batchId: this.$route.query.id || paySalaryInfoId,
          transferBuildDetailAddVOList: selectedListTemp,
          type: info.type
        });
        // this.confirmLoading = false;
        this.$notification.success({ message: "操作成功" });
        this.$emit("update:visible", false);
        if (data.failTransferAccountsDetailAddDTOList.length > 0) {
          // data.transferAccountsBatchVO.id
          this.$emit("upDate", data.failTransferAccountsDetailAddDTOList);
        } else {
          this.$emit("upDate");
        }
      } catch (err) {
        console.log("error log --> ", err);
        // this.confirmLoading = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.employee-selector {
  height: 310px;
  margin-top: 2px;
  padding-right: 10px;
  overflow: auto;
}
.tit {
  width: 352px;
  // font-size: 12px;
  // font-weight: 400;
  // color: #767885;
  display: flex;
  // & > div:nth-child(1) {
  //   color: #ff7085;
  // }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  height: 40px;
  .tree-item-div {
    display: flex;
    align-items: center;

    .overflowsWL {
      width: 190px;
    }
    .overflowsWLM {
      width: 100px;
    }
    .overflowsWR {
      width: 176px;
    }
    .overflows {
      display: inline-block;
      margin-right: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 382px;
    padding-right: 22px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 346px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  .employee-selector-block2 {
    width: 274px;
    border-radius: 8px;
    background-color: #f4f6fa;
    padding: 12px 4px 12px 12px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
    }
    .employee-selector {
      height: 420px;
      margin-top: 2px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        height: 40px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
.iconStyle {
  font-size: 18px;
  color: var(--primary);
}
.selectStyle {
  color: var(--primary);
}
.checkboxs {
  position: relative;
  & > span {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 20px;
    height: 20px;
  }
}
.hrs-tabs {
  padding: 8px 12px;
  border-radius: 14px;
  color: #a6a8b4;
  background: #f4f6fa;
  margin-right: 12px;
  font-weight: 400;
  cursor: pointer;
}
.hrs-tabs-selectStyle {
  color: var(--primary);
  font-weight: 500;
  background: var(--primary10);
}
</style>
